<?php

namespace app\common\model\user;

use app\common\model\Config;
use app\common\model\DiamondLog;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Exception;
use think\Model;


class Vipinfo extends Model
{

    // 表名
    protected $table = 'user_vip_info';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'expiretime_text'
    ];

    //VIP充值 / 续费
    public static function buy_vip($user_id, $vip, $form)
    {
        $user = User::find($user_id);
        switch ($form) {
            case 1:
                $log = new MoneyLog();
                $worth = 'money';
                $form_name = '购买';
                $parent = User::where(['id' => $user['parent_id']])->find();
                if ($parent) {
                    $value = Config::where('name', 'vip_ratio')->value('value', 0);
                    $ratio = $value / 100;
                    $diamond = bcmul($vip[$worth], $ratio, 2);
                    if ($diamond > 0) {
                        $parent_before = $parent['diamond'];
                        $parent_after = function_exists('bcadd') ? bcadd($parent['diamond'], $diamond, 2) : $parent['diamond'] + $diamond;
                        DiamondLog::create([
                            'user_id' => $parent['id'], 'diamond' => $diamond,
                            'before' => $parent_before, 'after' => $parent_after,
                            'type' => 5, 'memo' => '会员卡推广收益:' . $user_id
                        ]);
                        $parent->save(['diamond' => $parent_after]);
                    }
                }
                break;
            case 2:
                $log = new ScoreLog();
                $worth = 'score';
                $form_name = '兑换';
                break;
            default:
                throw new Exception('当前购买方式有误');
        }
        if ($user) {
            if ($user[$worth] < $vip[$worth]) {
                throw new Exception("当前余额不足");
            }

            $sn = get_sn($user_id);
            $now = time();
            $time = $vip['num'] * 24 * 3600;

            $insert = [
                'vip_id' => $vip['id'],
                'log_sn' => "VIP_" . $sn,
                'form' => $form,
                'num' => $vip['num'],
                'user_id' => $user_id,
                'vip_type_id' => $vip['type_id'],
                'price' => $vip[$worth]
            ];
            //Vip购买记录
            Viplog::create($insert);

            //增加VIP时效
            if ($user['vip_end_time'] > $now) {
                $vip_end_time = $time + $user['vip_end_time'];//续费
            } else {
                $vip_end_time = $time + $now;//从当前时间开始计算
            }

            $create_info = true;//新增判断值
            $type = $vip['type_id'];//当前更新的type
            $discount = Viptype::where("id", $vip['type_id'])->value("serve_discount", 0);//当前折扣

            //VIP信息校检
            $vip_info = self::where(['user_id' => $user_id])->select();
            if ($vip_info) {
                foreach ($vip_info as $value) {
                    //当前充值VIP类型检测
                    if ($vip['type_id'] == $value['vip_type']) {
                        $create_info = false;
                    }
                    //判断是续费还是重新充值 所有有效期内类型的VIP同时增时
                    if ($value->expiretime > $now) {
                        self::where("id", $value->id)->setInc("expiretime", $time);
                    } else {
                        self::update(['expiretime' => $vip_end_time], ['id' => $value->id]);
                    }

                    //当前VIP最新折扣
                    $vip_discount = Viptype::where("id", $value['vip_type'])->value("serve_discount", 0);
                    if ($discount > $vip_discount) {
                        $type = $value['vip_type'];
                    }
                }
            }

            if ($create_info) {
                self::create([
                    'user_id' => $user_id,
                    'vip_type' => $vip['type_id'],
                    'serve_discount' => $discount,
                    'num' => $vip['num'],
                    'expiretime' => $vip_end_time
                ]);
            }
            $after = $user[$worth];
            if ($vip[$worth] > 0) {
                $after = function_exists('bcadd') ? bcadd($user[$worth], -$vip[$worth], 2) : $user[$worth] - $vip[$worth];
                $after = $form == 2 ? intval($after) : $after;
                //扣款
                $before = $user[$worth];
                $log->insert([
                    $worth => $vip[$worth], 'user_id' => $user['id'],
                    'before' => $before, 'after' => $after,
                    'type' => 1, 'memo' => "{$form_name}VIP"
                ]);
            }
            $user->save([$worth => $after, 'vip_end_time' => $vip_end_time, 'vip_type_id' => $type]);
        } else {
            throw new Exception("当前用户有误");
        }
    }

    public static function vip_check($user)
    {
        $time = time();
        $info = self::where(['user_id' => $user['id'], 'expiretime' => ['>', $time]])
            ->order('id DESC')->find();

        if (!$info) {
            User::update(['vip_type_id' => 0], ['id' => $user['id']]);
            $user['vip_type_id'] = 0;
        } else {
            $user['vip_logo'] = Viptype::where('id', $info['vip_type'])->value('sign');
            $user['vip_name'] = Viptype::where('id', $info['vip_type'])->value('name');
            //等级检测
            if ($info['vip_type'] != $user['vip_type_id']) {
                User::update(['vip_type_id' => $info['vip_type']], ['id' => $user['id']]);
                $user['vip_type_id'] = $info['vip_type'];
            }
        }

        //时间转换
        $user['vip_end_time'] = date('Y-m-d H:i:s', $user['vip_end_time']);

        return $user;
    }

    public function getExpiretimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['expiretime']) ? $data['expiretime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected function setExpiretimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
}
